\chapter{Chapter 6: Web Development and APIs}

\section{Overview}

Web Development \& APIs represents one of the most versatile and impactful task types in Claude Code development. These tasks span from creating simple web interfaces to building complex full-stack applications with real-time features, REST APIs, authentication systems, and database integration. This task type encompasses both frontend user interfaces and backend services, making it crucial for modern software development.

\subsection{\textbf{Key Characteristics}}
\begin{itemize}
\item \textbf{Scope}: Web applications, REST APIs, dashboards, real-time interfaces, authentication systems, database integration
\item \textbf{Complexity}: Medium to High (3-5 on complexity scale)
\item \textbf{Typical Duration}: Single session to multiple sessions spanning days or weeks
\item \textbf{Success Factors}: Clear architecture planning, proper separation of concerns, robust error handling, security considerations
\item \textbf{Common Patterns}: Requirements Analysis → Architecture Design → Backend/API Development → Frontend Implementation → Integration → Testing → Deployment
\end{itemize}

\subsection{\textbf{When to Use This Task Type}}
\begin{itemize}
\item Building web applications and user interfaces
\item Creating REST APIs and web services
\item Developing monitoring dashboards and admin interfaces
\item Implementing real-time features (WebSockets, live updates)
\item Setting up authentication and authorization systems
\item Integrating with databases and external APIs
\item Creating full-stack applications with frontend and backend components
\item Building MCP (Model Context Protocol) servers with web interfaces
\item Developing data visualization and analytics platforms
\end{itemize}

\subsection{\textbf{Typical Complexity and Duration}}

\textbf{Simple Web Applications (Complexity 3):}
\begin{itemize}
\item Basic static websites or simple dashboards
\item Single-page applications with minimal interactivity
\item Basic REST APIs with CRUD operations
\item Duration: 2-6 hours, single session
\end{itemize}

\textbf{Medium Web Applications (Complexity 4):}
\begin{itemize}
\item Interactive dashboards with real-time updates
\item Multi-page applications with user authentication
\item REST APIs with complex business logic
\item Database integration and data persistence
\item Duration: 1-3 days across multiple sessions
\end{itemize}

\textbf{Complex Web Applications (Complexity 5):}
\begin{itemize}
\item Full-stack applications with multiple microservices
\item Real-time collaborative features
\item Advanced authentication and authorization
\item Integration with multiple external APIs
\item Performance optimization and scalability considerations
\item Duration: 1-4 weeks across many sessions
\end{itemize}

\section{Real-World Examples from Session Analysis}

\subsection{\textbf{Example 1: ArXiv Subscription Platform - Full-Stack React Application}}

\textbf{Initial Context:}
Working directory: \textbackslash\{\}texttt\{/home/linden/Downloads/arxiv\_paper/RINN/data/arxiv\_subscription\_platform\}

\textbf{Key Development Challenges:}
\begin{lstlisting}
when I login it report error: \\textcolor{red}{$\\times$} Sign in failed: Error: Invalid credentials
    signIn AuthProvider.tsx:232
    handleLogin LoginDialog.tsx:172
\end{lstlisting}

\textbf{Frontend Issues Encountered:}
\begin{lstlisting}
[eslint] 
src/hooks/usePapers.ts
  Line 99:6:   React Hook useCallback has a missing dependency: 'mockPapers'
  Line 123:6:  React Hook useCallback has a missing dependency: 'mockPapers'

src/pages/Browse.tsx
  Line 55:6:  React Hook useEffect has missing dependencies: 'fetchPapers' and 'filters'
\end{lstlisting}

\textbf{Development Approach Taken:}
\begin{itemize}
\item \textbf{Frontend Development}: React-based SPA with TypeScript
\item \textbf{Authentication System}: Custom authentication with login/signup functionality  
\item \textbf{State Management}: React hooks with complex dependency management
\item \textbf{API Integration}: Supabase backend integration for data persistence
\item \textbf{Error Handling}: Comprehensive error logging and user feedback
\item \textbf{Development Workflow}: Frontend and backend served on separate ports (3001, 3002)
\end{itemize}

\textbf{Key Development Pattern:}
\begin{enumerate}
\item \textbf{Architecture Setup}: Separate frontend and backend services
\item \textbf{Authentication Implementation}: User login/signup with credential validation
\item \textbf{State Management}: Complex React hooks for paper management
\item \textbf{API Integration}: Real-time data synchronization with backend
\item \textbf{Error Debugging}: Systematic log analysis and issue resolution
\end{enumerate}

\subsection{\textbf{Example 2: Claude Code Usage Monitor - Web Dashboard with Real-Time Features}}

\textbf{Initial Prompt Context:}
\begin{lstlisting}
add --serve to enable frontend website, optimize its exhibit performance
\end{lstlisting}

\textbf{Development Approach Taken:}
\begin{itemize}
\item \textbf{Backend API}: FastAPI-based web server with comprehensive statistics collection
\item \textbf{Real-time Updates}: WebSocket integration for live dashboard updates
\item \textbf{Performance Optimization}: Caching systems with 30-second TTL for statistics
\item \textbf{CLI Integration}: Web server as an extension to existing CLI tool
\item \textbf{Data Visualization}: Interactive charts and tables for session analysis
\end{itemize}

\textbf{Key Development Pattern:}
\begin{enumerate}
\item \textbf{CLI to Web Extension}: Adding web capabilities to existing command-line tool
\item \textbf{Real-time Architecture}: WebSocket implementation for live updates
\item \textbf{Performance Optimization}: Strategic caching for heavy data operations
\item \textbf{API Design}: RESTful endpoints with both human-readable and JSON outputs
\item \textbf{Frontend Integration}: Template-based HTML interface with dynamic updates
\end{enumerate}

\subsection{\textbf{Example 3: Frontend React Application - Development Debugging}}

\textbf{Initial Context:}
Working directory: \textbackslash\{\}texttt\{/home/linden/Downloads/arxiv\_paper/RINN/data/arxiv\_subscription\_platform/frontend\}

\textbf{Development Challenges:}
\begin{lstlisting}
NetworkError when attempting to fetch resource
\end{lstlisting}

\textbf{Configuration Issues:}
\begin{lstlisting}
src/lib/supabase.ts:3:const supabaseUrl = 'https://jeudfsekrmlyuvcxljlb.supabase.co'
src/lib/supabase.ts:4:const supabaseAnonKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
\end{lstlisting}

\textbf{Development Approach Taken:}
\begin{itemize}
\item \textbf{Environment Configuration}: Proper .env file setup for API credentials
\item \textbf{Error Handling}: Network error debugging and resolution
\item \textbf{Code Quality}: ESLint rule compliance and React hooks optimization
\item \textbf{Development Environment}: npm run start with proper error logging
\end{itemize}

\textbf{Key Development Pattern:}
\begin{enumerate}
\item \textbf{Environment Setup}: Secure credential management with .env files
\item \textbf{Error Diagnosis}: Network debugging and API connectivity testing
\item \textbf{Code Quality}: Linting rule compliance and best practices
\item \textbf{Development Workflow}: Local development server with hot reloading
\end{enumerate}

\subsection{\textbf{Example 4: MCP Server Development - API Service Integration}}

\textbf{Initial Context:}
\begin{lstlisting}
秘塔AI搜索的MCP服务 - MCP service based on Model Context Protocol providing intelligent search and Q&A capabilities
\end{lstlisting}

\textbf{API Integration Requirements:}
\begin{itemize}
\item \textbf{Multi-dimensional Search}: Web pages, documents, papers, images, videos, podcasts
\item \textbf{Content Reading}: URL content extraction with JSON and Markdown output
\item \textbf{Intelligent Q&A}: RAG-based question answering service
\end{itemize}

\textbf{Development Approach Taken:}
\begin{itemize}
\item \textbf{API Design}: RESTful endpoints for search and content retrieval
\item \textbf{Authentication}: Bearer token-based API authentication
\item \textbf{Service Integration}: External API integration with proper error handling
\item \textbf{Configuration Management}: API key management and environment setup
\end{itemize}

\textbf{Key Development Pattern:}
\begin{enumerate}
\item \textbf{API Architecture}: RESTful service design with multiple endpoints
\item \textbf{Authentication Implementation}: Secure API key management
\item \textbf{External Integration}: Third-party API integration patterns
\item \textbf{Error Handling}: Comprehensive error management and fallbacks
\item \textbf{Documentation}: API documentation with usage examples
\end{enumerate}

\section{Templates and Procedures}

\subsection{Web Application Planning Template}

Use this template to systematically plan web application development:

\begin{lstlisting}[language=bash]
\section{Web Application Development Planning Template}

\subsection{Project Overview}
\textbf{Application Name}: [descriptive-app-name]
\textbf{Primary Purpose}: [clear description of main functionality]
\textbf{Target Users}: [end-users, admins, developers, etc.]
\textbf{Application Type}: [SPA, Multi-page, Progressive Web App, etc.]
\textbf{Complexity Level}: [3-5 based on scope and requirements]
\textbf{Estimated Duration}: [single session / multiple days / weeks]

\subsection{Architecture Requirements}
\textbf{Frontend Technology}:
\begin{itemize}
\item [ ] Framework: [React, Vue, Angular, vanilla JS]
\item [ ] Language: [TypeScript, JavaScript]
\item [ ] Build Tool: [Vite, Webpack, Create React App]
\item [ ] Styling: [CSS, Sass, styled-components, Tailwind]
\end{itemize}

\textbf{Backend Technology}:
\begin{itemize}
\item [ ] Framework: [FastAPI, Flask, Django, Express.js]
\item [ ] Language: [Python, JavaScript, TypeScript]
\item [ ] Server: [Uvicorn, Gunicorn, PM2]
\end{itemize}

\textbf{Database & Storage}:
\begin{itemize}
\item [ ] Database: [PostgreSQL, MongoDB, SQLite, Supabase]
\item [ ] ORM/ODM: [SQLAlchemy, Mongoose, Prisma]
\item [ ] Caching: [Redis, Memcached, in-memory]
\end{itemize}

\subsection{Feature Requirements}
\textbf{Core Features}:
\begin{itemize}
\item [ ] [Primary feature 1]
\item [ ] [Primary feature 2]
\item [ ] [Primary feature 3]
\end{itemize}

\textbf{User Management}:
\begin{itemize}
\item [ ] User registration and authentication
\item [ ] Role-based access control
\item [ ] Profile management
\item [ ] Password reset functionality
\end{itemize}

\textbf{API Requirements}:
\begin{itemize}
\item [ ] RESTful API design
\item [ ] API documentation (OpenAPI/Swagger)
\item [ ] Rate limiting and throttling
\item [ ] Request/response logging
\end{itemize}

\textbf{Real-time Features}:
\begin{itemize}
\item [ ] WebSocket connections
\item [ ] Live data updates
\item [ ] Push notifications
\item [ ] Real-time collaboration
\end{itemize}

\subsection{Security Considerations}
\textbf{Authentication & Authorization}:
\begin{itemize}
\item [ ] JWT token management
\item [ ] Session handling
\item [ ] Multi-factor authentication
\item [ ] OAuth integration
\end{itemize}

\textbf{API Security}:
\begin{itemize}
\item [ ] CORS configuration
\item [ ] Input validation and sanitization
\item [ ] SQL injection prevention
\item [ ] XSS protection
\end{itemize}

\textbf{Data Protection}:
\begin{itemize}
\item [ ] Sensitive data encryption
\item [ ] Environment variable management
\item [ ] HTTPS/TLS configuration
\item [ ] Data backup and recovery
\end{itemize}

\subsection{Performance Requirements}
\textbf{Frontend Performance}:
\begin{itemize}
\item [ ] Bundle size optimization
\item [ ] Code splitting and lazy loading
\item [ ] Image optimization
\item [ ] Browser caching strategies
\end{itemize}

\textbf{Backend Performance}:
\begin{itemize}
\item [ ] Database query optimization
\item [ ] API response caching
\item [ ] Connection pooling
\item [ ] Background task processing
\end{itemize}

\textbf{Monitoring & Analytics}:
\begin{itemize}
\item [ ] Application performance monitoring
\item [ ] Error tracking and logging
\item [ ] User analytics
\item [ ] System health checks
\end{itemize}

\subsection{Development Environment}
\textbf{Local Development}:
\begin{itemize}
\item [ ] Docker containerization
\item [ ] Environment variable management
\item [ ] Database seeding and migrations
\item [ ] Hot reloading and development server
\end{itemize}

\textbf{Testing Strategy}:
\begin{itemize}
\item [ ] Unit testing framework
\item [ ] Integration testing
\item [ ] End-to-end testing
\item [ ] API testing tools
\end{itemize}

\textbf{Deployment Strategy}:
\begin{itemize}
\item [ ] Production environment setup
\item [ ] CI/CD pipeline
\item [ ] Domain and SSL configuration
\item [ ] Backup and monitoring setup
\end{itemize}
\end{lstlisting}

\subsection{API Development Template}

Use this template for systematic REST API development:

\begin{lstlisting}[language=bash]
\section{REST API Development Template}

\subsection{API Overview}
\textbf{API Name}: [descriptive-api-name]
\textbf{Version}: [v1, v2, etc.]
\textbf{Base URL}: [https://api.example.com/v1]
\textbf{Authentication}: [JWT, API Key, OAuth2]

\subsection{API Design Principles}
\textbf{RESTful Design}:
\begin{itemize}
\item [ ] Use HTTP methods appropriately (GET, POST, PUT, DELETE)
\item [ ] Follow resource-based URL patterns
\item [ ] Implement proper HTTP status codes
\item [ ] Use consistent response formats
\end{itemize}

\textbf{Resource Planning}:
\begin{itemize}
\item [ ] Identify main resources and entities
\item [ ] Define resource relationships
\item [ ] Plan URL structure and endpoints
\item [ ] Design request/response schemas
\end{itemize}

\subsection{Endpoint Documentation Template}
\end{lstlisting}
\subsection{[Resource Name] Endpoints}

\subsubsection{GET /api/v1/[resource]}
\textbf{Description}: Retrieve list of [resource]
\textbf{Authentication}: Required
\textbf{Parameters}:
\begin{itemize}
\item \texttt{limit} (query, optional): Number of items to return (default: 10)
\item \texttt{offset} (query, optional): Number of items to skip (default: 0)
\item \texttt{filter} (query, optional): Filter criteria
\end{itemize}

\textbf{Response}:
\begin{lstlisting}[language=bash]
{
  "status": "success",
  "data": [
    {
      "id": 1,
      "field1": "value1",
      "field2": "value2",
      "created\_at": "2023-01-01T00:00:00Z"

  ],
  "pagination": {
    "total": 100,
    "limit": 10,
    "offset": 0


\end{lstlisting}

\textbf{Error Responses}:
\begin{itemize}
\item \texttt{400 Bad Request}: Invalid parameters
\item \texttt{401 Unauthorized}: Missing or invalid authentication
\item \texttt{500 Internal Server Error}: Server error
\end{itemize}
\begin{lstlisting}
\subsection{Authentication Implementation Template}
\textbf{JWT Authentication Pattern}:
\end{lstlisting}

\begin{lstlisting}[language=python]
# Authentication middleware example
def authenticate\_request(request):
    """Validate JWT token and extract user information"""
    try:
        auth\_header = request.headers.get('Authorization')
        if not auth\_header or not auth\_header.startswith('Bearer '):
            raise AuthenticationError("Missing or invalid authorization header")
        
        token = auth\_header.split(' ')[1]
        payload = jwt.decode(token, SECRET\_KEY, algorithms=['HS256'])
        user\_id = payload.get('user\_id')
        
        \# Validate user exists and is active
        user = get\_user\_by\_id(user\_id)
        if not user or not user.is\_active:
            raise AuthenticationError("Invalid user")
        
        return user
    except jwt.ExpiredSignatureError:
        raise AuthenticationError("Token has expired")
    except jwt.InvalidTokenError:
        raise AuthenticationError("Invalid token")
\begin{lstlisting}
\subsection{Error Handling Template}
\textbf{Standardized Error Response Format}:
\end{lstlisting}json
\{
  "status": "error",
  "error": \{
    "code": "VALIDATION\_ERROR",
    "message": "Invalid input data",
    "details": \{
      "field": "email",
      "issue": "Invalid email format"
    \}
  \},
  "request\_id": "uuid-here"
\}
\begin{lstlisting}
\textbf{Error Handling Implementation}:
\end{lstlisting}python
class APIError(Exception):
    """Base API error class"""
    def \textbackslash\{\}textbf\{init\}(self, message, status\_code=500, error\_code=None):
        self.message = message
        self.status\_code = status\_code
        self.error\_code = error\_code
        super().\textbackslash\{\}textbf\{init\}(message)

def handle\_api\_error(error, request\_id):
    """Standardized error response handler"""
    return \{
        "status": "error",
        "error": \{
            "code": error.error\_code or "INTERNAL\_ERROR",
            "message": error.message,
            "details": getattr(error, 'details', None)
        \},
        "request\_id": request\_id
    \}, error.status\_code
\begin{lstlisting}
\subsection{Database Integration Template}
\textbf{Database Model Example}:
\end{lstlisting}python
from sqlalchemy import Column, Integer, String, DateTime, Boolean
from sqlalchemy.ext.declarative import declarative\_base

Base = declarative\_base()

class User(Base):
    \textbf{tablename} = 'users'
    
    id = Column(Integer, primary\_key=True)
    email = Column(String(255), unique=True, nullable=False)
    password\_hash = Column(String(255), nullable=False)
    is\_active = Column(Boolean, default=True)
    created\_at = Column(DateTime, default=datetime.utcnow)
    updated\_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def to\_dict(self):
        """Convert model to dictionary for JSON serialization"""
        return \{
            'id': self.id,
            'email': self.email,
            'is\_active': self.is\_active,
            'created\_at': self.created\_at.isoformat(),
            'updated\_at': self.updated\_at.isoformat()
        \}
\begin{lstlisting}

\end{lstlisting}

\subsection{Frontend Development Template}

Use this template for systematic frontend development:

\begin{lstlisting}[language=bash]
\section{Frontend Development Template}

\subsection{Project Setup}
\textbf{Framework Configuration}:
\begin{itemize}
\item [ ] Initialize project with chosen framework
\item [ ] Configure TypeScript/JavaScript settings
\item [ ] Set up linting and formatting (ESLint, Prettier)
\item [ ] Configure build tools and bundlers
\end{itemize}

\textbf{Directory Structure}:
\end{lstlisting}
src/
├── components/          \# Reusable UI components
│   ├── common/         \# Generic components (Button, Input)
│   └── specific/       \# Feature-specific components
├── pages/              \# Page-level components
├── hooks/              \# Custom React hooks (if using React)
├── services/           \# API communication layer
├── utils/              \# Utility functions
├── styles/             \# Global styles and themes
├── types/              \# TypeScript type definitions
└── config/             \# Configuration files
\begin{lstlisting}
\subsection{Component Development Pattern}
\textbf{Component Template}:
\end{lstlisting}typescript
import React, \{ useState, useEffect \} from 'react';
import \{ ComponentProps \} from '../types';

interface Props extends ComponentProps \{
  title: string;
  onAction: (data: any) => void;
\}

export const ComponentName: React.FC<Props> = (\{ 
  title, 
  onAction, 
  ...props 
\}) => \{
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => \{
    // Component initialization logic
  \}, []);

  const handleAction = async () => \{
    try \{
      setLoading(true);
      setError(null);
      
      const result = await apiCall();
      onAction(result);
    \} catch (err) \{
      setError(err.message);
    \} finally \{
      setLoading(false);
    \}
  \};

  if (loading) return <LoadingSpinner />;
  if (error) return <ErrorMessage error=\{error\} />;

  return (
    <div className="component-wrapper">
      <h2>\{title\}</h2>
      \{/\textbackslash\{\}textit\{ Component JSX \}/\}
    </div>
  );
\};
\begin{lstlisting}
\subsection{API Integration Pattern}
\textbf{API Service Layer}:
\end{lstlisting}typescript
// services/api.ts
class ApiService \{
  private baseURL: string;
  private authToken: string | null = null;

  constructor(baseURL: string) \{
    this.baseURL = baseURL;
  \}

  setAuthToken(token: string) \{
    this.authToken = token;
  \}

  private async request<T>(
    endpoint: string, 
    options: RequestInit = \{\}
  ): Promise<T> \{
    const url = \textbackslash\{\}texttt\{\$\{this.baseURL\}\$\{endpoint\}\};
    const config: RequestInit = \{
      headers: \{
        'Content-Type': 'application/json',
        ...(this.authToken \&\& \{ Authorization: \textbackslash\{\}texttt\{Bearer \$\{this.authToken\}\} \}),
        ...options.headers,
      \},
      ...options,
    \};

    try \{
      const response = await fetch(url, config);
      
      if (!response.ok) \{
        throw new Error(\textbackslash\{\}texttt\{HTTP error! status: \$\{response.status\}\});
      \}
      
      return await response.json();
    \} catch (error) \{
      console.error('API request failed:', error);
      throw error;
    \}
  \}

  async get<T>(endpoint: string): Promise<T> \{
    return this.request<T>(endpoint);
  \}

  async post<T>(endpoint: string, data: any): Promise<T> \{
    return this.request<T>(endpoint, \{
      method: 'POST',
      body: JSON.stringify(data),
    \});
  \}

  async put<T>(endpoint: string, data: any): Promise<T> \{
    return this.request<T>(endpoint, \{
      method: 'PUT',
      body: JSON.stringify(data),
    \});
  \}

  async delete<T>(endpoint: string): Promise<T> \{
    return this.request<T>(endpoint, \{
      method: 'DELETE',
    \});
  \}
\}

export const apiService = new ApiService(process.env.REACT\_APP\_API\_BASE\_URL || '');
\begin{lstlisting}
\subsection{State Management Template}
\textbf{React Context for Global State}:
\end{lstlisting}typescript
// contexts/AppContext.tsx
import React, \{ createContext, useContext, useReducer, ReactNode \} from 'react';

interface AppState \{
  user: User | null;
  loading: boolean;
  error: string | null;
\}

type AppAction = 
  | \{ type: 'SET\_USER'; payload: User \}
  | \{ type: 'SET\_LOADING'; payload: boolean \}
  | \{ type: 'SET\_ERROR'; payload: string | null \}
  | \{ type: 'LOGOUT' \};

const appReducer = (state: AppState, action: AppAction): AppState => \{
  switch (action.type) \{
    case 'SET\_USER':
      return \{ ...state, user: action.payload \};
    case 'SET\_LOADING':
      return \{ ...state, loading: action.payload \};
    case 'SET\_ERROR':
      return \{ ...state, error: action.payload \};
    case 'LOGOUT':
      return \{ ...state, user: null \};
    default:
      return state;
  \}
\};

const AppContext = createContext<\{
  state: AppState;
  dispatch: React.Dispatch<AppAction>;
\} | null>(null);

export const AppProvider: React.FC<\{ children: ReactNode \}> = (\{ children \}) => \{
  const [state, dispatch] = useReducer(appReducer, \{
    user: null,
    loading: false,
    error: null,
  \});

  return (
    <AppContext.Provider value=\{\{ state, dispatch \}\}>
      \{children\}
    </AppContext.Provider>
  );
\};

export const useApp = () => \{
  const context = useContext(AppContext);
  if (!context) \{
    throw new Error('useApp must be used within an AppProvider');
  \}
  return context;
\};
\begin{lstlisting}

\end{lstlisting}

\subsection{Full-Stack Integration Template}

Use this template for coordinating frontend and backend development:

\begin{lstlisting}[language=bash]
\section{Full-Stack Integration Template}

\subsection{Development Environment Setup}
\textbf{Local Development Configuration}:
\end{lstlisting}json
// package.json - Frontend proxy configuration
\{
  "name": "frontend",
  "proxy": "http://localhost:3001",
  "scripts": \{
    "start": "react-scripts start",
    "dev": "npm start"
  \}
\}
\begin{lstlisting}
\textbf{Backend Development Server}:
\end{lstlisting}

\begin{lstlisting}[language=python]
# main.py - FastAPI with CORS configuration
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI(title="API Server", version="1.0.0")

app.add\_middleware(
    CORSMiddleware,
    allow\_origins=["http://localhost:3000"],  \# Frontend URL
    allow\_credentials=True,
    allow\_methods=["*"],
    allow\_headers=["*"],
)

if \textbackslash\{\}textbf\{name\} == "\textbackslash\{\}textbf\{main\}":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=3001, reload=True)
\begin{lstlisting}
\subsection{Database Integration Template}
\textbf{Database Configuration}:
\end{lstlisting}

\begin{lstlisting}[language=python]
# database.py
from sqlalchemy import create\_engine
from sqlalchemy.ext.declarative import declarative\_base
from sqlalchemy.orm import sessionmaker
import os

DATABASE\_URL = os.getenv("DATABASE\_URL", "sqlite:///./app.db")

engine = create\_engine(DATABASE\_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative\_base()

def get\_db():
    """Database dependency for FastAPI"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
\begin{lstlisting}
\textbf{Data Access Layer}:
\end{lstlisting}

\begin{lstlisting}[language=python]
# repositories/user\_repository.py
from sqlalchemy.orm import Session
from typing import Optional, List
from models import User
from schemas import UserCreate, UserUpdate

class UserRepository:
    def \textbackslash\{\}textbf\{init\}(self, db: Session):
        self.db = db
    
    def create(self, user\_data: UserCreate) -> User:
        """Create a new user"""
        user = User(**user\_data.dict())
        self.db.add(user)
        self.db.commit()
        self.db.refresh(user)
        return user
    
    def get\_by\_id(self, user\_id: int) -> Optional[User]:
        """Get user by ID"""
        return self.db.query(User).filter(User.id == user\_id).first()
    
    def get\_by\_email(self, email: str) -> Optional[User]:
        """Get user by email"""
        return self.db.query(User).filter(User.email == email).first()
    
    def update(self, user\_id: int, user\_data: UserUpdate) -> Optional[User]:
        """Update user"""
        user = self.get\_by\_id(user\_id)
        if user:
            for field, value in user\_data.dict(exclude\_unset=True).items():
                setattr(user, field, value)
            self.db.commit()
            self.db.refresh(user)
        return user
    
    def delete(self, user\_id: int) -> bool:
        """Delete user"""
        user = self.get\_by\_id(user\_id)
        if user:
            self.db.delete(user)
            self.db.commit()
            return True
        return False
\begin{lstlisting}
\subsection{Real-Time Features Template}
\textbf{WebSocket Implementation}:
\end{lstlisting}

\begin{lstlisting}[language=python]
# websocket\_manager.py
from fastapi import WebSocket, WebSocketDisconnect
from typing import List
import json

class WebSocketManager:
    def \textbackslash\{\}textbf\{init\}(self):
        self.active\_connections: List[WebSocket] = []
    
    async def connect(self, websocket: WebSocket):
        """Accept new WebSocket connection"""
        await websocket.accept()
        self.active\_connections.append(websocket)
    
    def disconnect(self, websocket: WebSocket):
        """Remove WebSocket connection"""
        self.active\_connections.remove(websocket)
    
    async def send\_personal\_message(self, message: str, websocket: WebSocket):
        """Send message to specific client"""
        await websocket.send\_text(message)
    
    async def broadcast(self, message: str):
        """Broadcast message to all connected clients"""
        for connection in self.active\_connections:
            await connection.send\_text(message)
    
    async def broadcast\_json(self, data: dict):
        """Broadcast JSON data to all connected clients"""
        message = json.dumps(data)
        await self.broadcast(message)

# FastAPI WebSocket endpoint
from fastapi import APIRouter, WebSocket, WebSocketDisconnect

router = APIRouter()
manager = WebSocketManager()

@router.websocket("/ws")
async def websocket\_endpoint(websocket: WebSocket):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive\_text()
            \# Process received data
            response = \{"type": "response", "data": f"Received: \{data\}"\}
            await manager.send\_personal\_message(json.dumps(response), websocket)
    except WebSocketDisconnect:
        manager.disconnect(websocket)
\begin{lstlisting}
\textbf{Frontend WebSocket Integration}:
\end{lstlisting}typescript
// hooks/useWebSocket.ts
import \{ useEffect, useRef, useState \} from 'react';

interface UseWebSocketOptions \{
  onMessage?: (data: any) => void;
  onConnect?: () => void;
  onDisconnect?: () => void;
  onError?: (error: Event) => void;
\}

export const useWebSocket = (url: string, options: UseWebSocketOptions = \{\}) => \{
  const [isConnected, setIsConnected] = useState(false);
  const [lastMessage, setLastMessage] = useState<any>(null);
  const wsRef = useRef<WebSocket | null>(null);

  useEffect(() => \{
    const ws = new WebSocket(url);
    wsRef.current = ws;

    ws.onopen = () => \{
      setIsConnected(true);
      options.onConnect?.();
    \};

    ws.onmessage = (event) => \{
      try \{
        const data = JSON.parse(event.data);
        setLastMessage(data);
        options.onMessage?.(data);
      \} catch (error) \{
        console.error('Failed to parse WebSocket message:', error);
      \}
    \};

    ws.onclose = () => \{
      setIsConnected(false);
      options.onDisconnect?.();
    \};

    ws.onerror = (error) => \{
      options.onError?.(error);
    \};

    return () => \{
      ws.close();
    \};
  \}, [url]);

  const sendMessage = (data: any) => \{
    if (wsRef.current \&\& isConnected) \{
      wsRef.current.send(JSON.stringify(data));
    \}
  \};

  return \{
    isConnected,
    lastMessage,
    sendMessage,
  \};
\};
\begin{lstlisting}
\subsection{Testing and Quality Assurance Template}
\textbf{Backend Testing Setup}:
\end{lstlisting}

\begin{lstlisting}[language=python]
# tests/test\_api.py
import pytest
from fastapi.testclient import TestClient
from main import app
from database import get\_db
import os

client = TestClient(app)

# Test database configuration
os.environ["DATABASE\_URL"] = "sqlite:///./test.db"

def test\_create\_user():
    """Test user creation endpoint"""
    user\_data = \{
        "email": "test@example.com",
        "password": "testpass123"
    \}
    response = client.post("/api/v1/users", json=user\_data)
    assert response.status\_code == 201
    assert response.json()["email"] == user\_data["email"]

def test\_get\_user():
    """Test user retrieval endpoint"""
    \# First create a user
    user\_data = \{"email": "test2@example.com", "password": "testpass123"\}
    create\_response = client.post("/api/v1/users", json=user\_data)
    user\_id = create\_response.json()["id"]
    
    \# Then retrieve it
    response = client.get(f"/api/v1/users/\{user\_id\}")
    assert response.status\_code == 200
    assert response.json()["email"] == user\_data["email"]

def test\_authentication():
    """Test authentication flow"""
    \# Create user
    user\_data = \{"email": "auth@example.com", "password": "testpass123"\}
    client.post("/api/v1/users", json=user\_data)
    
    \# Login
    login\_data = \{"email": "auth@example.com", "password": "testpass123"\}
    response = client.post("/api/v1/auth/login", json=login\_data)
    assert response.status\_code == 200
    assert "access\_token" in response.json()
\begin{lstlisting}
\textbf{Frontend Testing Setup}:
\end{lstlisting}typescript
// tests/components/Component.test.tsx
import \{ render, screen, fireEvent, waitFor \} from '@testing-library/react';
import \{ ComponentName \} from '../ComponentName';
import \{ apiService \} from '../../services/api';

// Mock API service
jest.mock('../../services/api');
const mockApiService = apiService as jest.Mocked<typeof apiService>;

describe('ComponentName', () => \{
  beforeEach(() => \{
    jest.clearAllMocks();
  \});

  it('renders correctly', () => \{
    render(<ComponentName title="Test Title" onAction=\{jest.fn()\} />);
    expect(screen.getByText('Test Title')).toBeInTheDocument();
  \});

  it('handles action correctly', async () => \{
    const mockOnAction = jest.fn();
    const mockData = \{ id: 1, name: 'Test' \};
    mockApiService.get.mockResolvedValue(mockData);

    render(<ComponentName title="Test" onAction=\{mockOnAction\} />);
    
    fireEvent.click(screen.getByRole('button'));
    
    await waitFor(() => \{
      expect(mockOnAction).toHaveBeenCalledWith(mockData);
    \});
  \});

  it('handles errors gracefully', async () => \{
    const mockError = new Error('API Error');
    mockApiService.get.mockRejectedValue(mockError);

    render(<ComponentName title="Test" onAction=\{jest.fn()\} />);
    
    fireEvent.click(screen.getByRole('button'));
    
    await waitFor(() => \{
      expect(screen.getByText('API Error')).toBeInTheDocument();
    \});
  \});
\});
\begin{lstlisting}
\subsection{Deployment Configuration Template}
\textbf{Docker Configuration}:
\end{lstlisting}

\begin{lstlisting}[language=dockerfile]
# Dockerfile.backend
FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

EXPOSE 8000

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
\begin{lstlisting}

\end{lstlisting}

\begin{lstlisting}[language=dockerfile]
# Dockerfile.frontend
FROM node:18-alpine as build

WORKDIR /app
COPY package*.json ./
RUN npm install

COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
\begin{lstlisting}
\textbf{Docker Compose Configuration}:
\end{lstlisting}

\begin{lstlisting}[language=yaml]
# docker-compose.yml
version: '3.8'

services:
  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    ports:
\begin{itemize}
\item "8000:8000"
    environment:
\item DATABASE\_URL=postgresql://user:password@db:5432/appdb
    depends\_on:
\item db
    volumes:
\item ./backend:/app
\end{itemize}
  
  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
    ports:
\begin{itemize}
\item "3000:80"
    depends\_on:
\item backend
\end{itemize}
  
  db:
    image: postgres:13
    environment:
\begin{itemize}
\item POSTGRES\_USER=user
\item POSTGRES\_PASSWORD=password
\item POSTGRES\_DB=appdb
    volumes:
\item postgres\_data:/var/lib/postgresql/data
    ports:
\item "5432:5432"
\end{itemize}

volumes:
  postgres\_data:
\begin{lstlisting}

\end{lstlisting}

\section{Common Web Development Patterns}

\subsection{\textbf{Architecture Patterns}}

\textbf{1. MVC (Model-View-Controller) Pattern}
\begin{itemize}
\item \textbf{Model}: Database models and business logic
\item \textbf{View}: Frontend templates and components
\item \textbf{Controller}: API endpoints and request handlers
\item Used in: Django, Ruby on Rails, traditional web applications
\end{itemize}

\textbf{2. Component-Based Architecture}
\begin{itemize}
\item \textbf{Components}: Reusable UI elements with encapsulated logic
\item \textbf{State Management}: Centralized state with Redux, Context API, or Vuex
\item \textbf{Service Layer}: Separate API communication and business logic
\item Used in: React, Vue.js, Angular applications
\end{itemize}

\textbf{3. Microservices Architecture}
\begin{itemize}
\item \textbf{Service Separation}: Independent services for different business domains
\item \textbf{API Gateway}: Central entry point for all client requests
\item \textbf{Inter-service Communication}: REST APIs, message queues, or gRPC
\item Used in: Large-scale applications, distributed systems
\end{itemize}

\subsection{\textbf{Authentication and Authorization Patterns}}

\textbf{1. JWT (JSON Web Token) Authentication}
\begin{lstlisting}[language=Python]
# Implementation pattern
import jwt
from datetime import datetime, timedelta

def create\_access\_token(user\_id: int, expires\_delta: timedelta = None):
    """Create JWT access token"""
    if expires\_delta is None:
        expires\_delta = timedelta(hours=24)
    
    expire = datetime.utcnow() + expires\_delta
    payload = {
        "user\_id": user\_id,
        "exp": expire,
        "iat": datetime.utcnow()

    token = jwt.encode(payload, SECRET\_KEY, algorithm="HS256")
    return token

def verify\_token(token: str):
    """Verify and decode JWT token"""
    try:
        payload = jwt.decode(token, SECRET\_KEY, algorithms=["HS256"])
        user\_id = payload.get("user\_id")
        return user\_id
    except jwt.ExpiredSignatureError:
        raise ValueError("Token has expired")
    except jwt.InvalidTokenError:
        raise ValueError("Invalid token")
\end{lstlisting}

\textbf{2. Role-Based Access Control (RBAC)}
\begin{lstlisting}[language=Python]
# RBAC implementation pattern
from functools import wraps
from flask import g, abort

def require\_role(required\_role):
    """Decorator to require specific role for endpoint access"""
    def decorator(f):
        @wraps(f)
        def decorated\_function(\textit{args, }*kwargs):
            if not g.user or g.user.role != required\_role:
                abort(403)  # Forbidden
            return f(\textit{args, }*kwargs)
        return decorated\_function
    return decorator

# Usage
@app.route('/admin/users')
@require\_role('admin')
def admin\_users():
    return get\_all\_users()
\end{lstlisting}

\subsection{\textbf{Real-Time Communication Patterns}}

\textbf{1. WebSocket Pattern for Live Updates}
\begin{lstlisting}[language=Java]
// Frontend WebSocket client pattern
class WebSocketClient {
  constructor(url, handlers = {}) {
    this.url = url;
    this.handlers = handlers;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectDelay = 1000;

  connect() {
    this.ws = new WebSocket(this.url);
    
    this.ws.onopen = () => {
      console.log('WebSocket connected');
      this.reconnectAttempts = 0;
      this.handlers.onConnect?.();
    };
    
    this.ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      this.handlers.onMessage?.(data);
    };
    
    this.ws.onclose = () => {
      console.log('WebSocket disconnected');
      this.attemptReconnect();
    };
    
    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
      this.handlers.onError?.(error);
    };

  attemptReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      setTimeout(() => this.connect(), this.reconnectDelay);
      this.reconnectDelay *= 2; // Exponential backoff


  send(data) {
    if (this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data));



\end{lstlisting}

\textbf{2. Server-Sent Events (SSE) Pattern}
\begin{lstlisting}[language=Python]
# Backend SSE implementation
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio
import json

@app.get("/events")
async def stream\_events():
    """Server-Sent Events endpoint"""
    async def event\_generator():
        while True:
            # Get latest data
            data = await get\_latest\_data()
            
            # Format as SSE
            yield f"data: {json.dumps(data)}\n\n"
            
            # Wait before next update
            await asyncio.sleep(5)
    
    return StreamingResponse(
        event\_generator(),
        media\_type="text/plain",
        headers={"Cache-Control": "no-cache"}
    )
\end{lstlisting}

\subsection{\textbf{Database Integration Patterns}}

\textbf{1. Repository Pattern}
\begin{lstlisting}[language=Python]
# Repository pattern for data access abstraction
from abc import ABC, abstractmethod
from typing import List, Optional

class BaseRepository(ABC):
    @abstractmethod
    def create(self, entity): pass
    
    @abstractmethod
    def get\_by\_id(self, id): pass
    
    @abstractmethod
    def update(self, id, data): pass
    
    @abstractmethod
    def delete(self, id): pass
    
    @abstractmethod
    def list(self, **filters): pass

class SQLUserRepository(BaseRepository):
    def \textbf{init}(self, db\_session):
        self.db = db\_session
    
    def create(self, user\_data):
        user = User(**user\_data)
        self.db.add(user)
        self.db.commit()
        return user
    
    def get\_by\_id(self, user\_id):
        return self.db.query(User).filter(User.id == user\_id).first()
    
    # ... implement other methods
\end{lstlisting}

\textbf{2. Unit of Work Pattern}
\begin{lstlisting}[language=Python]
# Unit of Work pattern for transaction management
class UnitOfWork:
    def \textbf{init}(self, db\_session):
        self.db = db\_session
        self.users = SQLUserRepository(db\_session)
        self.orders = SQLOrderRepository(db\_session)
    
    def \textbf{enter}(self):
        return self
    
    def \textbf{exit}(self, exc\_type, exc\_val, exc\_tb):
        if exc\_type is None:
            self.commit()
        else:
            self.rollback()
    
    def commit(self):
        self.db.commit()
    
    def rollback(self):
        self.db.rollback()

# Usage
with UnitOfWork(db\_session) as uow:
    user = uow.users.create(user\_data)
    order = uow.orders.create(order\_data)
    # Automatic commit on successful completion
\end{lstlisting}

\section{Best Practices}

\subsection{\textbf{How to Structure Web Development Conversations with Claude}}

\textbf{1. Start with Clear Requirements}
\begin{lstlisting}[language=bash]
Good prompt structure:
"I need to build a [type of application] that allows users to [core functionality]. 
The key features are: [list features]. I want to use [technology stack] and deploy to [platform].
Please help me plan the architecture and start with [specific starting point]."

Example:
"I need to build a task management web application that allows teams to create, 
assign, and track tasks. Key features are: user authentication, task CRUD operations, 
real-time updates, and dashboard analytics. I want to use React frontend with 
FastAPI backend and PostgreSQL database. Please help me plan the architecture 
and start with the database schema design."
\end{lstlisting}

\textbf{2. Break Down Complex Applications}
\begin{lstlisting}[language=bash]
Instead of: "Build me a complete e-commerce website"
Use: "Let's start with user authentication system for an e-commerce site. 
I need registration, login, password reset, and user profile management. 
Once this is working, we'll add product catalog functionality."
\end{lstlisting}

\textbf{3. Specify Technology Preferences Early}
\begin{lstlisting}[language=bash]
"For this project, I prefer:
\begin{itemize}
\item Frontend: React with TypeScript
\item Backend: FastAPI with Python
\item Database: PostgreSQL
\item Authentication: JWT tokens
\item Deployment: Docker containers
\end{itemize}
Please design the architecture with these technologies."
\end{lstlisting}

\subsection{\textbf{When to Use Different Web Technologies and Frameworks}}

\textbf{Frontend Framework Selection:}

\textbf{React - Choose When:}
\begin{itemize}
\item Building single-page applications (SPAs)
\item Need component reusability and large ecosystem
\item Team has JavaScript/TypeScript experience
\item Want flexibility in architecture decisions
\end{itemize}

\textbf{Vue.js - Choose When:}
\begin{itemize}
\item Building both SPAs and traditional web apps
\item Want gentle learning curve and clear documentation
\item Need progressive adoption in existing projects
\item Prefer opinionated but flexible framework
\end{itemize}

\textbf{Angular - Choose When:}
\begin{itemize}
\item Building large enterprise applications
\item Team has TypeScript and OOP background
\item Need comprehensive built-in tooling
\item Want strict architectural patterns
\end{itemize}

\textbf{Backend Framework Selection:}

\textbf{FastAPI - Choose When:}
\begin{itemize}
\item Building REST APIs with Python
\item Need automatic API documentation
\item Want high performance and async support
\item Prefer modern Python features and type hints
\end{itemize}

\textbf{Django - Choose When:}
\begin{itemize}
\item Building full-stack web applications quickly
\item Need comprehensive built-in features (admin, ORM)
\item Want "batteries included" approach
\item Building content management systems
\end{itemize}

\textbf{Flask - Choose When:}
\begin{itemize}
\item Building lightweight APIs or small applications
\item Need flexibility and minimal initial setup
\item Want to choose your own components
\item Building microservices
\end{itemize}

\textbf{Express.js - Choose When:}
\begin{itemize}
\item Building Node.js applications
\item Team has strong JavaScript skills
\item Need real-time features with Socket.io
\item Want consistent language across stack
\end{itemize}

\subsection{\textbf{Security Considerations and Implementation}}

\textbf{1. Input Validation and Sanitization}
\begin{lstlisting}[language=Python]
# Input validation example
from pydantic import BaseModel, validator
import re

class UserRegistration(BaseModel):
    email: str
    password: str
    username: str
    
    @validator('email')
    def validate\_email(cls, v):
        pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        if not re.match(pattern, v):
            raise ValueError('Invalid email format')
        return v.lower()
    
    @validator('password')
    def validate\_password(cls, v):
        if len(v) < 8:
            raise ValueError('Password must be at least 8 characters')
        if not re.search(r'[A-Z]', v):
            raise ValueError('Password must contain uppercase letter')
        if not re.search(r'[a-z]', v):
            raise ValueError('Password must contain lowercase letter')
        if not re.search(r'\d', v):
            raise ValueError('Password must contain digit')
        return v
    
    @validator('username')
    def validate\_username(cls, v):
        if not re.match(r'^[a-zA-Z0-9_]{3,20}$', v):
            raise ValueError('Username must be 3-20 characters, alphanumeric and underscores only')
        return v
\end{lstlisting}

\textbf{2. Authentication Security}
\begin{lstlisting}[language=Python]
# Secure password hashing
from passlib.context import CryptContext
import secrets

pwd\_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def hash\_password(password: str) -> str:
    """Hash password securely"""
    return pwd\_context.hash(password)

def verify\_password(plain\_password: str, hashed\_password: str) -> bool:
    """Verify password against hash"""
    return pwd\_context.verify(plain\_password, hashed\_password)

def generate\_secure\_token() -> str:
    """Generate cryptographically secure random token"""
    return secrets.token\_urlsafe(32)
\end{lstlisting}

\textbf{3. API Security Headers}
\begin{lstlisting}[language=Python]
# FastAPI security middleware
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()

# CORS configuration
app.add\_middleware(
    CORSMiddleware,
    allow\_origins=["https://yourdomain.com"],  # Never use "*" in production
    allow\_credentials=True,
    allow\_methods=["GET", "POST", "PUT", "DELETE"],
    allow\_headers=["*"],
)

# Trusted host middleware
app.add\_middleware(
    TrustedHostMiddleware,
    allowed\_hosts=["yourdomain.com", "*.yourdomain.com"]
)

# Custom security headers middleware
@app.middleware("http")
async def add\_security\_headers(request, call\_next):
    response = await call\_next(request)
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    response.headers["X-XSS-Protection"] = "1; mode=block"
    response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
    return response
\end{lstlisting}

\subsection{\textbf{Testing and Quality Assurance Procedures}}

\textbf{1. API Testing Strategy}
\begin{lstlisting}[language=Python]
# Comprehensive API testing
import pytest
from fastapi.testclient import TestClient
from unittest.mock import patch

class TestUserAPI:
    def setup\_method(self):
        """Setup test client and test data"""
        self.client = TestClient(app)
        self.test\_user = {
            "email": "test@example.com",
            "password": "SecurePass123",
            "username": "testuser"

    def test\_user\_registration\_success(self):
        """Test successful user registration"""
        response = self.client.post("/api/v1/auth/register", json=self.test\_user)
        assert response.status\_code == 201
        assert response.json()["email"] == self.test\_user["email"]
        assert "password" not in response.json()  # Password should not be returned
    
    def test\_user\_registration\_duplicate\_email(self):
        """Test registration with duplicate email"""
        # First registration
        self.client.post("/api/v1/auth/register", json=self.test\_user)
        
        # Duplicate registration
        response = self.client.post("/api/v1/auth/register", json=self.test\_user)
        assert response.status\_code == 400
        assert "already exists" in response.json()["message"].lower()
    
    def test\_login\_success(self):
        """Test successful login"""
        # Register user first
        self.client.post("/api/v1/auth/register", json=self.test\_user)
        
        # Login
        login\_data = {"email": self.test\_user["email"], "password": self.test\_user["password"]}
        response = self.client.post("/api/v1/auth/login", json=login\_data)
        
        assert response.status\_code == 200
        assert "access\_token" in response.json()
        assert response.json()["token\_type"] == "bearer"
    
    def test\_protected\_endpoint\_without\_token(self):
        """Test accessing protected endpoint without token"""
        response = self.client.get("/api/v1/users/me")
        assert response.status\_code == 401
    
    def test\_protected\_endpoint\_with\_valid\_token(self):
        """Test accessing protected endpoint with valid token"""
        # Register and login
        self.client.post("/api/v1/auth/register", json=self.test\_user)
        login\_response = self.client.post("/api/v1/auth/login", 
                                        json={"email": self.test\_user["email"], 
                                              "password": self.test\_user["password"]})
        
        token = login\_response.json()["access\_token"]
        headers = {"Authorization": f"Bearer {token}"}
        
        response = self.client.get("/api/v1/users/me", headers=headers)
        assert response.status\_code == 200
        assert response.json()["email"] == self.test\_user["email"]
\end{lstlisting}

\textbf{2. Frontend Testing Strategy}
\begin{lstlisting}
// Component testing with React Testing Library
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import { AuthProvider } from '../contexts/AuthContext';
import LoginForm from '../LoginForm';

const renderWithProviders = (component) => {
  return render(
    <BrowserRouter>
      <AuthProvider>
        {component}
      </AuthProvider>
    </BrowserRouter>
  );
};

describe('LoginForm Component', () => {
  it('renders login form correctly', () => {
    renderWithProviders(<LoginForm />);
    
    expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
    expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /log in/i })).toBeInTheDocument();
  });

  it('displays validation errors for empty fields', async () => {
    renderWithProviders(<LoginForm />);
    
    fireEvent.click(screen.getByRole('button', { name: /log in/i }));
    
    await waitFor(() => {
      expect(screen.getByText(/email is required/i)).toBeInTheDocument();
      expect(screen.getByText(/password is required/i)).toBeInTheDocument();
    });
  });

  it('displays error message for invalid credentials', async () => {
    renderWithProviders(<LoginForm />);
    
    fireEvent.change(screen.getByLabelText(/email/i), { 
      target: { value: 'wrong@example.com' } 
    });
    fireEvent.change(screen.getByLabelText(/password/i), { 
      target: { value: 'wrongpassword' } 
    });
    fireEvent.click(screen.getByRole('button', { name: /log in/i }));
    
    await waitFor(() => {
      expect(screen.getByText(/invalid credentials/i)).toBeInTheDocument();
    });
  });

  it('redirects to dashboard on successful login', async () => {
    const mockNavigate = jest.fn();
    jest.mock('react-router-dom', () => ({
      ...jest.requireActual('react-router-dom'),
      useNavigate: () => mockNavigate,
    }));

    renderWithProviders(<LoginForm />);
    
    fireEvent.change(screen.getByLabelText(/email/i), { 
      target: { value: 'user@example.com' } 
    });
    fireEvent.change(screen.getByLabelText(/password/i), { 
      target: { value: 'password123' } 
    });
    fireEvent.click(screen.getByRole('button', { name: /log in/i }));
    
    await waitFor(() => {
      expect(mockNavigate).toHaveBeenCalledWith('/dashboard');
    });
  });
});
\end{lstlisting}

\textbf{3. End-to-End Testing with Playwright}
\begin{lstlisting}
// e2e/login.spec.ts
import { test, expect } from '@playwright/test';

test.describe('User Authentication Flow', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/');
  });

  test('user can register and login successfully', async ({ page }) => {
    // Navigate to registration
    await page.click('text=Sign Up');
    
    // Fill registration form
    await page.fill('[data-testid="email"]', 'test@example.com');
    await page.fill('[data-testid="username"]', 'testuser');
    await page.fill('[data-testid="password"]', 'SecurePass123');
    await page.fill('[data-testid="confirm-password"]', 'SecurePass123');
    
    // Submit registration
    await page.click('[data-testid="register-button"]');
    
    // Verify registration success
    await expect(page.locator('text=Registration successful')).toBeVisible();
    
    // Login with new account
    await page.fill('[data-testid="login-email"]', 'test@example.com');
    await page.fill('[data-testid="login-password"]', 'SecurePass123');
    await page.click('[data-testid="login-button"]');
    
    // Verify login success and redirect to dashboard
    await expect(page).toHaveURL('/dashboard');
    await expect(page.locator('text=Welcome, testuser')).toBeVisible();
  });

  test('displays error for invalid login credentials', async ({ page }) => {
    await page.click('text=Log In');
    
    await page.fill('[data-testid="login-email"]', 'wrong@example.com');
    await page.fill('[data-testid="login-password"]', 'wrongpassword');
    await page.click('[data-testid="login-button"]');
    
    await expect(page.locator('text=Invalid credentials')).toBeVisible();
  });
});
\end{lstlisting}

\section{Advanced Techniques}

\subsection{\textbf{Complex Web Application Architectures}}

\textbf{1. Micro-frontend Architecture}
\begin{lstlisting}
// Module Federation Setup for Micro-frontends
// webpack.config.js for shell application
const ModuleFederationPlugin = require('@module-federation/webpack');

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'shell',
      remotes: {
        userManagement: 'userManagement@http://localhost:3001/remoteEntry.js',
        productCatalog: 'productCatalog@http://localhost:3002/remoteEntry.js',
        orderManagement: 'orderManagement@http://localhost:3003/remoteEntry.js',
      },
    }),
  ],
};

// Dynamic micro-frontend loading
import React, { Suspense } from 'react';

const UserManagement = React.lazy(() => import('userManagement/UserApp'));
const ProductCatalog = React.lazy(() => import('productCatalog/ProductApp'));
const OrderManagement = React.lazy(() => import('orderManagement/OrderApp'));

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/users/*" element={
          <Suspense fallback={<div>Loading User Management...</div>}>
            <UserManagement />
          </Suspense>
        } />
        <Route path="/products/*" element={
          <Suspense fallback={<div>Loading Product Catalog...</div>}>
            <ProductCatalog />
          </Suspense>
        } />
        <Route path="/orders/*" element={
          <Suspense fallback={<div>Loading Order Management...</div>}>
            <OrderManagement />
          </Suspense>
        } />
      </Routes>
    </Router>
  );

\end{lstlisting}

\textbf{2. Event-Driven Architecture}
\begin{lstlisting}[language=Python]
# Event-driven system with message queues
from abc import ABC, abstractmethod
import json
import asyncio
from typing import List, Callable

class Event(ABC):
    """Base event class"""
    def \textbf{init}(self, event\_type: str, data: dict):
        self.event\_type = event\_type
        self.data = data
        self.timestamp = datetime.utcnow()

class EventHandler(ABC):
    """Abstract event handler"""
    @abstractmethod
    async def handle(self, event: Event):
        pass

class EventBus:
    """Event bus for managing events and handlers"""
    def \textbf{init}(self):
        self.handlers: dict[str, List[EventHandler]] = {}
    
    def subscribe(self, event\_type: str, handler: EventHandler):
        """Subscribe handler to event type"""
        if event\_type not in self.handlers:
            self.handlers[event\_type] = []
        self.handlers[event\_type].append(handler)
    
    async def publish(self, event: Event):
        """Publish event to all subscribed handlers"""
        if event.event\_type in self.handlers:
            tasks = []
            for handler in self.handlers[event.event\_type]:
                tasks.append(handler.handle(event))
            await asyncio.gather(*tasks)

# Example usage
class UserRegisteredEvent(Event):
    def \textbf{init}(self, user\_id: int, email: str):
        super().\textbf{init}('user\_registered', {
            'user\_id': user\_id,
            'email': email
        })

class EmailNotificationHandler(EventHandler):
    async def handle(self, event: Event):
        if event.event\_type == 'user\_registered':
            await self.send\_welcome\_email(event.data['email'])
    
    async def send\_welcome\_email(self, email: str):
        # Send welcome email logic
        print(f"Sending welcome email to {email}")

class UserAnalyticsHandler(EventHandler):
    async def handle(self, event: Event):
        if event.event\_type == 'user\_registered':
            await self.track\_user\_registration(event.data['user\_id'])
    
    async def track\_user\_registration(self, user\_id: int):
        # Analytics tracking logic
        print(f"Tracking registration for user {user\_id}")

# Setup event bus
event\_bus = EventBus()
event\_bus.subscribe('user\_registered', EmailNotificationHandler())
event\_bus.subscribe('user\_registered', UserAnalyticsHandler())

# Usage in API endpoint
@app.post("/api/v1/users")
async def create\_user(user\_data: UserCreate):
    user = create\_user\_in\_database(user\_data)
    
    # Publish event
    event = UserRegisteredEvent(user.id, user.email)
    await event\_bus.publish(event)
    
    return user
\end{lstlisting}

\subsection{\textbf{Microservices Integration}}

\textbf{1. API Gateway Pattern}
\begin{lstlisting}[language=Python]
# API Gateway with FastAPI and service discovery
from fastapi import FastAPI, HTTPException
from httpx import AsyncClient
import consul
from typing import Dict, Optional

class ServiceRegistry:
    """Service discovery using Consul"""
    def \textbf{init}(self, consul\_host: str = "localhost", consul\_port: int = 8500):
        self.consul = consul.Consul(host=consul\_host, port=consul\_port)
    
    def register\_service(self, name: str, host: str, port: int, health\_check\_url: str):
        """Register service with Consul"""
        self.consul.agent.service.register(
            name=name,
            service\_id=f"{name}-{host}-{port}",
            address=host,
            port=port,
            check=consul.Check.http(health\_check\_url, interval="10s")
        )
    
    def discover\_service(self, service\_name: str) -> Optional[Dict]:
        """Discover service endpoint"""
        services = self.consul.health.service(service\_name, passing=True)[1]
        if services:
            service = services[0]
            return {
                "host": service["Service"]["Address"],
                "port": service["Service"]["Port"]

        return None

class APIGateway:
    """API Gateway with load balancing and circuit breaker"""
    def \textbf{init}(self, service\_registry: ServiceRegistry):
        self.service\_registry = service\_registry
        self.circuit\_breakers = {}
        self.client = AsyncClient()
    
    async def route\_request(self, service\_name: str, path: str, method: str, **kwargs):
        """Route request to appropriate service"""
        service\_info = self.service\_registry.discover\_service(service\_name)
        if not service\_info:
            raise HTTPException(status\_code=503, detail=f"Service {service\_name} not available")
        
        url = f"http://{service\_info['host']}:{service\_info['port']}{path}"
        
        try:
            response = await self.client.request(method, url, **kwargs)
            return response.json()
        except Exception as e:
            raise HTTPException(status\_code=502, detail=f"Service {service\_name} error: {str(e)}")

# Gateway setup
app = FastAPI(title="API Gateway")
service\_registry = ServiceRegistry()
gateway = APIGateway(service\_registry)

@app.api\_route("/users/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def user\_service\_proxy(path: str, request: Request):
    """Proxy requests to user service"""
    return await gateway.route\_request(
        "user-service",
        f"/{path}",
        request.method,
        json=await request.json() if request.method in ["POST", "PUT"] else None
    )

@app.api\_route("/orders/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def order\_service\_proxy(path: str, request: Request):
    """Proxy requests to order service"""
    return await gateway.route\_request(
        "order-service",
        f"/{path}",
        request.method,
        json=await request.json() if request.method in ["POST", "PUT"] else None
    )
\end{lstlisting}

\textbf{2. Circuit Breaker Pattern}
\begin{lstlisting}[language=Python]
# Circuit breaker for service resilience
import asyncio
from enum import Enum
from datetime import datetime, timedelta

class CircuitState(Enum):
    CLOSED = "closed"
    OPEN = "open"
    HALF\_OPEN = "half\_open"

class CircuitBreaker:
    """Circuit breaker implementation"""
    def \textbf{init}(self, failure\_threshold: int = 5, recovery\_timeout: int = 30):
        self.failure\_threshold = failure\_threshold
        self.recovery\_timeout = recovery\_timeout
        self.failure\_count = 0
        self.last\_failure\_time = None
        self.state = CircuitState.CLOSED
    
    async def call(self, func, \textit{args, }*kwargs):
        """Execute function with circuit breaker protection"""
        if self.state == CircuitState.OPEN:
            if self.\_should\_attempt\_reset():
                self.state = CircuitState.HALF\_OPEN
            else:
                raise Exception("Circuit breaker is OPEN")
        
        try:
            result = await func(\textit{args, }*kwargs)
            self.\_on\_success()
            return result
        except Exception as e:
            self.\_on\_failure()
            raise e
    
    def \_should\_attempt\_reset(self) -> bool:
        """Check if circuit breaker should attempt reset"""
        if self.last\_failure\_time is None:
            return False
        
        time\_since\_failure = datetime.utcnow() - self.last\_failure\_time
        return time\_since\_failure >= timedelta(seconds=self.recovery\_timeout)
    
    def \_on\_success(self):
        """Handle successful call"""
        self.failure\_count = 0
        self.state = CircuitState.CLOSED
    
    def \_on\_failure(self):
        """Handle failed call"""
        self.failure\_count += 1
        self.last\_failure\_time = datetime.utcnow()
        
        if self.failure\_count >= self.failure\_threshold:
            self.state = CircuitState.OPEN

# Usage with service calls
user\_service\_breaker = CircuitBreaker(failure\_threshold=3, recovery\_timeout=30)

async def call\_user\_service(endpoint: str, data: dict = None):
    """Call user service with circuit breaker protection"""
    async def service\_call():
        async with AsyncClient() as client:
            response = await client.post(f"http://user-service/{endpoint}", json=data)
            response.raise\_for\_status()
            return response.json()
    
    return await user\_service\_breaker.call(service\_call)
\end{lstlisting}

\subsection{\textbf{Real-Time Data Streaming}}

\textbf{1. WebSocket with Redis Pub/Sub}
\begin{lstlisting}[language=Python]
# Real-time updates with Redis Pub/Sub
import redis.asyncio as redis
import json
from fastapi import WebSocket

class RealTimeManager:
    """Manage real-time updates with Redis Pub/Sub"""
    def \textbf{init}(self, redis\_url: str = "redis://localhost:6379"):
        self.redis\_client = redis.from\_url(redis\_url)
        self.active\_connections: Dict[str, Set[WebSocket]] = {}
    
    async def connect\_user(self, user\_id: str, websocket: WebSocket):
        """Connect user WebSocket"""
        await websocket.accept()
        
        if user\_id not in self.active\_connections:
            self.active\_connections[user\_id] = set()
        self.active\_connections[user\_id].add(websocket)
        
        # Subscribe to user-specific channel
        await self.\_subscribe\_to\_user\_updates(user\_id)
    
    async def disconnect\_user(self, user\_id: str, websocket: WebSocket):
        """Disconnect user WebSocket"""
        if user\_id in self.active\_connections:
            self.active\_connections[user\_id].discard(websocket)
            if not self.active\_connections[user\_id]:
                del self.active\_connections[user\_id]
    
    async def publish\_to\_user(self, user\_id: str, message: dict):
        """Publish message to specific user"""
        channel = f"user:{user\_id}:updates"
        await self.redis\_client.publish(channel, json.dumps(message))
    
    async def publish\_to\_channel(self, channel: str, message: dict):
        """Publish message to channel"""
        await self.redis\_client.publish(channel, json.dumps(message))
    
    async def \_subscribe\_to\_user\_updates(self, user\_id: str):
        """Subscribe to user-specific updates"""
        pubsub = self.redis\_client.pubsub()
        await pubsub.subscribe(f"user:{user\_id}:updates")
        
        asyncio.create\_task(self.\_handle\_messages(user\_id, pubsub))
    
    async def \_handle\_messages(self, user\_id: str, pubsub):
        """Handle incoming messages from Redis"""
        async for message in pubsub.listen():
            if message["type"] == "message":
                data = json.loads(message["data"])
                await self.\_send\_to\_user(user\_id, data)
    
    async def \_send\_to\_user(self, user\_id: str, message: dict):
        """Send message to all user connections"""
        if user\_id in self.active\_connections:
            disconnected = set()
            for websocket in self.active\_connections[user\_id]:
                try:
                    await websocket.send\_json(message)
                except:
                    disconnected.add(websocket)
            
            # Remove disconnected websockets
            for ws in disconnected:
                self.active\_connections[user\_id].discard(ws)

# WebSocket endpoint
realtime\_manager = RealTimeManager()

@app.websocket("/ws/{user\_id}")
async def websocket\_endpoint(websocket: WebSocket, user\_id: str):
    await realtime\_manager.connect\_user(user\_id, websocket)
    try:
        while True:
            data = await websocket.receive\_text()
            # Handle incoming messages from client
            message = json.loads(data)
            await process\_client\_message(user\_id, message)
    except WebSocketDisconnect:
        await realtime\_manager.disconnect\_user(user\_id, websocket)

# Example: Publish update when data changes
@app.post("/api/v1/tasks")
async def create\_task(task\_data: TaskCreate):
    task = create\_task\_in\_database(task\_data)
    
    # Notify assigned user in real-time
    update\_message = {
        "type": "task\_assigned",
        "task": task.to\_dict()

    await realtime\_manager.publish\_to\_user(task.assigned\_user\_id, update\_message)
    
    return task
\end{lstlisting}

\subsection{\textbf{Performance Monitoring and Optimization}}

\textbf{1. Application Performance Monitoring}
\begin{lstlisting}[language=Python]
# APM with custom metrics and tracing
import time
import asyncio
from functools import wraps
from typing import Dict, Any
import structlog

logger = structlog.get\_logger()

class PerformanceMonitor:
    """Performance monitoring and metrics collection"""
    def \textbf{init}(self):
        self.metrics = {
            "request\_count": 0,
            "request\_duration": [],
            "error\_count": 0,
            "active\_connections": 0

        self.thresholds = {
            "slow\_query": 1.0,  # seconds
            "high\_memory": 500 \textit{ 1024 } 1024,  # 500MB
            "error\_rate": 0.05  # 5%

    def track\_request(self, func):
        """Decorator to track request performance"""
        @wraps(func)
        async def wrapper(\textit{args, }*kwargs):
            start\_time = time.time()
            self.metrics["request\_count"] += 1
            
            try:
                result = await func(\textit{args, }*kwargs)
                duration = time.time() - start\_time
                self.metrics["request\_duration"].append(duration)
                
                if duration > self.thresholds["slow\_query"]:
                    logger.warning("Slow request detected", 
                                 function=func.\textbf{name}, 
                                 duration=duration)
                
                return result
            except Exception as e:
                self.metrics["error\_count"] += 1
                logger.error("Request error", 
                           function=func.\textbf{name}, 
                           error=str(e))
                raise
        
        return wrapper
    
    def get\_metrics(self) -> Dict[str, Any]:
        """Get current performance metrics"""
        if self.metrics["request\_duration"]:
            avg\_duration = sum(self.metrics["request\_duration"]) / len(self.metrics["request\_duration"])
            max\_duration = max(self.metrics["request\_duration"])
        else:
            avg\_duration = 0
            max\_duration = 0
        
        error\_rate = (self.metrics["error\_count"] / max(self.metrics["request\_count"], 1))
        
        return {
            "request\_count": self.metrics["request\_count"],
            "error\_count": self.metrics["error\_count"],
            "error\_rate": error\_rate,
            "average\_duration": avg\_duration,
            "max\_duration": max\_duration,
            "active\_connections": self.metrics["active\_connections"],
            "health\_status": "healthy" if error\_rate < self.thresholds["error\_rate"] else "degraded"

# Usage
monitor = PerformanceMonitor()

@app.get("/api/v1/users/{user\_id}")
@monitor.track\_request
async def get\_user(user\_id: int):
    user = await get\_user\_from\_database(user\_id)
    return user

@app.get("/health")
async def health\_check():
    """Health check endpoint with performance metrics"""
    return monitor.get\_metrics()
\end{lstlisting}

\textbf{2. Database Query Optimization}
\begin{lstlisting}[language=Python]
# Database query optimization patterns
from sqlalchemy import text, event, func
from sqlalchemy.orm import Session
from contextlib import asynccontextmanager
import time

class QueryOptimizer:
    """Database query optimization utilities"""
    
    @staticmethod
    def optimize\_user\_queries(db: Session):
        """Example of query optimization techniques"""
        
        # Bad: N+1 query problem
        # users = db.query(User).all()
        # for user in users:
        #     orders = user.orders  # This executes N additional queries
        
        # Good: Eager loading to avoid N+1
        users\_with\_orders = db.query(User).options(
            joinedload(User.orders)
        ).all()
        
        # Good: Use select\_related for related data
        users\_with\_profile = db.query(User).join(UserProfile).all()
        
        # Good: Pagination for large datasets
        page\_size = 20
        offset = 0
        paginated\_users = db.query(User)\
                           .offset(offset)\
                           .limit(page\_size)\
                           .all()
        
        return users\_with\_orders, users\_with\_profile, paginated\_users
    
    @staticmethod
    def bulk\_operations(db: Session):
        """Efficient bulk operations"""
        
        # Bulk insert - much faster than individual inserts
        users\_data = [
            {"email": f"user{i}@example.com", "username": f"user{i}"}
            for i in range(1000)
        ]
        db.bulk\_insert\_mappings(User, users\_data)
        
        # Bulk update
        db.query(User).filter(User.is\_active == False)\
                     .update({"last\_login": None}, synchronize\_session=False)
        
        # Batch processing for large operations
        batch\_size = 100
        total\_users = db.query(func.count(User.id)).scalar()
        
        for offset in range(0, total\_users, batch\_size):
            batch = db.query(User).offset(offset).limit(batch\_size).all()
            for user in batch:
                # Process each user
                user.processed = True
            db.commit()

# Query monitoring
@event.listens\_for(engine, "before\_cursor\_execute")
def receive\_before\_cursor\_execute(conn, cursor, statement, parameters, context, executemany):
    context.\_query\_start\_time = time.time()

@event.listens\_for(engine, "after\_cursor\_execute")  
def receive\_after\_cursor\_execute(conn, cursor, statement, parameters, context, executemany):
    total = time.time() - context.\_query\_start\_time
    if total > 0.5:  # Log slow queries
        logger.warning("Slow query detected", 
                      query=statement[:100], 
                      duration=total)
\end{lstlisting}

\textbf{3. Caching Strategies}
\begin{lstlisting}[language=Python]
# Multi-level caching implementation
import json
import asyncio
from typing import Optional, Any, Callable
import redis.asyncio as redis
from functools import wraps

class CacheManager:
    """Multi-level cache manager with Redis and in-memory"""
    
    def \textbf{init}(self, redis\_url: str = "redis://localhost:6379"):
        self.redis\_client = redis.from\_url(redis\_url)
        self.memory\_cache = {}  # Simple in-memory cache
        self.cache\_stats = {"hits": 0, "misses": 0}
    
    async def get(self, key: str) -> Optional[Any]:
        """Get value from cache (memory first, then Redis)"""
        # Check memory cache first
        if key in self.memory\_cache:
            self.cache\_stats["hits"] += 1
            return self.memory\_cache[key]["value"]
        
        # Check Redis cache
        value = await self.redis\_client.get(key)
        if value:
            self.cache\_stats["hits"] += 1
            parsed\_value = json.loads(value)
            # Store in memory cache for faster access
            self.memory\_cache[key] = {"value": parsed\_value, "timestamp": time.time()}
            return parsed\_value
        
        self.cache\_stats["misses"] += 1
        return None
    
    async def set(self, key: str, value: Any, ttl: int = 3600):
        """Set value in both memory and Redis cache"""
        # Store in Redis with TTL
        await self.redis\_client.setex(key, ttl, json.dumps(value))
        
        # Store in memory cache
        self.memory\_cache[key] = {"value": value, "timestamp": time.time()}
    
    async def delete(self, key: str):
        """Delete from both caches"""
        await self.redis\_client.delete(key)
        self.memory\_cache.pop(key, None)
    
    def cache\_result(self, ttl: int = 3600, key\_func: Optional[Callable] = None):
        """Decorator to cache function results"""
        def decorator(func):
            @wraps(func)
            async def wrapper(\textit{args, }*kwargs):
                # Generate cache key
                if key\_func:
                    cache\_key = key\_func(\textit{args, }*kwargs)
                else:
                    cache\_key = f"{func.\textbf{name}}:{hash(str(args) + str(kwargs))}"
                
                # Try to get from cache
                cached\_result = await self.get(cache\_key)
                if cached\_result is not None:
                    return cached\_result
                
                # Execute function and cache result
                result = await func(\textit{args, }*kwargs)
                await self.set(cache\_key, result, ttl)
                return result
            
            return wrapper
        return decorator

# Usage examples
cache\_manager = CacheManager()

@cache\_manager.cache\_result(ttl=1800, key\_func=lambda user\_id: f"user\_profile:{user\_id}")
async def get\_user\_profile(user\_id: int):
    """Get user profile with caching"""
    user = await db.query(User).filter(User.id == user\_id).first()
    return user.to\_dict() if user else None

@cache\_manager.cache\_result(ttl=300)  # 5 minutes
async def get\_popular\_products():
    """Get popular products with shorter cache time"""
    products = await db.query(Product)\
                     .filter(Product.is\_popular == True)\
                     .limit(10)\
                     .all()
    return [p.to\_dict() for p in products]

# Cache invalidation strategy
@app.post("/api/v1/users/{user\_id}/profile")
async def update\_user\_profile(user\_id: int, profile\_data: UserProfileUpdate):
    """Update user profile and invalidate cache"""
    updated\_user = await update\_user\_in\_database(user\_id, profile\_data)
    
    # Invalidate cache
    await cache\_manager.delete(f"user\_profile:{user\_id}")
    
    return updated\_user
\end{lstlisting}

This comprehensive chapter provides developers with the knowledge, templates, and patterns needed to successfully build web applications and APIs using Claude Code. The real-world examples demonstrate proven approaches, while the templates provide reusable structures for common web development scenarios.
